app.controller('userCtrl', function($rootScope,$scope, httpService, toaster, $filter, $parse, $timeout,$localStorage) {
    $scope.count=0;
    $scope.RecordType = wtSys.Emun.RecordType; //工作记录类型
    $scope.queryParam={
        beginTime:moment().format(wtSys.Emun.DateFormat.Date),
        endTime:moment().format(wtSys.Emun.DateFormat.Date)
    }
    //定义
    
    $scope.searchList = [{
        "typeName": "组别",
        "typeList": [
            { "Id": 1, "Name": "动力值班组" },
            { "Id": 2, "Name": "网络值班组" },
        ],
        isRadio:true
    }, ];
    // 初始化查询变量
    $scope.initParam = function() {
            $scope.userList = [];
            $scope.page = 1;
            $scope.busy = false;
            $scope.limit = 10;
            $scope.isGetDetailTag = true; //第一次默认加载第一条记录右侧信息
        }
        //编辑用户弹框处理
    $scope.edit = function(Id, index) {
        // 还原表单以及表单值
        $scope.userForm.$setPristine();
        if (Id || Id == 0) {
            $scope.userId = Id;
            $scope.index = index;
            $scope.isAdd = false;
            $scope.editModalTitle = "修改用户";
            $scope.getUserDetail(Id);
        } else {
            $scope.userId = null;
            $scope.index = null;
            $scope.userModel = {
                "UnitId": 0,
                "RoleId": "",
                "Icon": "",
                "Name": "",
                "Phone": "",
                "UserName": "",
                "Password": "",
                "Dept": "",
                "Lat": 9.1,
                "Lng": 10.1,
                "Email": "",
                "Groups": []
            }
            $scope.isAdd = true;
            $scope.editModalTitle = "新增用户";
        }
        $('#editModal').modal('show');
    };
    //编辑用户表单提交
    $scope.userFormSubmit = function() {
            var path = "/user";
            var type = "POST";
            if ($scope.userId) {
                path = "/user/" + $scope.userId;
                type = "PUT";
            }
            $scope.userForm.$invalid = true;
            httpService.request(type, path, $scope.userModel, function(result) {
                $scope.userForm.$invalid = false;
                toaster.pop("success", "提示", result.message);
                $('#editModal').modal('hide');
                // 更新列表数据
                var arr = $scope.userList;
                if ($scope.index != null && $scope.index >= 0) {
                    $scope.userModel.RoleName=_.result(_.find($scope.roleList, function(n){
                        return n.Id == $scope.userModel.RoleId;
                    }), 'Name');//修改RoleId对应的RoleName
                    arr[$scope.index] = $scope.userModel; //index存在直接更新
                    $scope.userDetailModel=angular.copy($scope.userModel);//更新右侧详情
                } else {
                    arr.unshift(result.data);
                    $scope.activeId = result.data.Id;
                }
                $scope.userList = arr;
		//同步用户名
	        if($localStorage.userInfo.id==$scope.userId){
	            $rootScope.userInfo.name=angular.copy($scope.userModel.Name);
	        }
            });
        }
        //删除用户弹框处理
    $scope.del = function(item, index){
        if($rootScope.userInfo.id==item.Id)
            return
        $scope.index = index;
        $scope.delModel = angular.copy(item);
        $('#delModal').modal('show');
    };
    //确认删除用户
    $scope.delConfirm = function(){
        $('#delModal').modal('hide');
        var path = '/user/' + $scope.delModel.Id;
        httpService.request("DELETE", path, null, function(result){
            toaster.pop("success", "提示", result.message);
            // 更新列表数据
            var arr = $scope.userList;
            arr.splice($scope.index, 1);
            //如果删除的是第一条数据,删除成功后重新设置activeId的值
            if($scope.index == 0){
                $scope.activeId = arr[0] ? arr[0].Id : null;
            }
        });
    }
        //编辑用户密码弹框处理
    $scope.editPsw = function(Id, userName) {
            $scope.userId = Id;
            $scope.userName = userName;
            //重置表单元素
            $scope.NewPassword = "";
            $scope.passwordagain = "";
            $scope.pswForm.$setPristine();
            $('#editPswModal').modal('show');
        }
        //修改密码表单提交
    $scope.pswFormSubmit = function() {
            var path = "/account/restpwd/" + $scope.userId;
            var type = "PUT";
            httpService.request(type, path, { "NewPassword": $scope.NewPassword }, function(result) {
                toaster.pop("success", "提示", result.message);
                $('#editPswModal').modal('hide');
                $scope.getUserList();
            });
        }
        //获取用户列表
    $scope.getUserList = function(isSearch) {
            if (isSearch) {
                $scope.initParam();
            }
            if ($scope.busy) return false;
            var key = $scope.key ? $scope.key : "";
            var groupid = "";
            if ($scope.searchModel) {
                var arr = $scope.searchModel;
                if (arr.length > 0) {
                    var newArr = [];
                    arr.forEach(function(item, index) {
                        newArr.push(item.Id);
                    });
                    groupid = newArr.join(",");
                }
            }
            var path = '/user?page=' + $scope.page + '&limit=' + $scope.limit + '&filter=key:' + key + ";groupid:" + groupid;
            $scope.busy = true;
            httpService.request("GET", path, null, function(result) {
                $scope.count=result.count;
                angular.forEach(result.data, function(data, i) {
                    $scope.userList.push(data);
                });
                if (result.data.length >= $scope.limit) {
                    $scope.busy = false;
                    $scope.page += 1;
                }
                //搜索结果为空 将activeId置为空
                if($scope.userList.length==0){
                    $scope.activeId=null;
                    return
                }
                if ($scope.userList.length > 0 && $scope.isGetDetailTag) {
                    $scope.isGetDetailTag = false;
                    var arr = $scope.userList;
                    $scope.activeId = arr[0].Id; //默认查询第一条记录的详情
                }
            });
        }
        //获取用户信息
    $scope.getUserDetail = function(Id, isRgt) {
            var path = '/user/' + Id;
            httpService.request("GET", path, null, function(result) {
                if (isRgt) {
                    $scope.userDetailModel = result.data;
                } else {
                    $scope.userModel = result.data;
                }
            });
        }
    //工作统计查询
    $scope.getUserWorkCount=function(){
        /*巡检提交数量 inspectioncount
        维修提交数量 servicingcount
        reportdangercount, --上报隐患数量
        assignservicingcount --被指派维修数量*/
        var path ='/user/jobaccount?uId='+$scope.activeId+'&beginTime='+moment($scope.queryParam.beginTime).format(wtSys.Emun.DateFormat.Date)+'&endTime='+moment($scope.queryParam.endTime).format(wtSys.Emun.DateFormat.Date);
        httpService.request("GET", path, null, function(result){
            var data=result.data;
            var timer=$timeout(function(){
                var myChart = echarts.init($('.bar-Chart')[0]);
                $scope.barOption = {
                    title: {
                        text: "工作统计",
                        x: 'left',
                        textStyle:{
                            fontWeight:'normal',
                        },
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: { // 坐标轴指示器，坐标轴触发有效
                            type: 'none' // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    legend: {
                        data: ['巡检提交', '上报隐患', '被指派维修', '维修提交'],
                        right: "3%",
                        top: 0
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: [{
                        type: 'category',
                        data: ['工作分类']
                    }],
                    yAxis: [{
                        type: 'value',
                        data: ['件'],
                    }],
                    series: [{
                        name: '巡检提交',
                        type: 'bar',
                        data: [data.InspectionCount],
                        barMaxWidth: 40,
                        barGap:'200%',
                        label: {
                            normal: {
                                show: true,
                                formatter:'{c}',
                                position:"top"
                            }
                        }
                    }, {
                        name: '上报隐患',
                        type: 'bar',
                        data: [data.ReportDangerCount],
                        barMaxWidth: 40,
                        barGap:'200%',
                        label: {
                            normal: {
                                show: true,
                                formatter:'{c}',
                                position:"top"
                            }
                        }
                    }, {
                        name: '被指派维修',
                        type: 'bar',
                        data: [data.AssignServicingCount],
                        barMaxWidth: 40,
                        barGap:'200%',
                        label: {
                            normal: {
                                show: true,
                                formatter:'{c}',
                                position:"top"
                            }
                        }
                    }, {
                        name: '维修提交',
                        type: 'bar',
                        data: [data.ServicingCount],
                        barMaxWidth: 40,
                        barGap:'200%',
                        label: {
                            normal: {
                                show: true,
                                formatter:'{c}',
                                position:"top"
                            }
                        }
                    }],
                    color:['#e9c162','#2ea2d1','#e06163','#70c27f']
                };
                myChart.setOption($scope.barOption);
                $timeout.cancel(timer);
            }, 0,false);
        });
    }
        //获取角色
    $scope.getRole = function() {
            var path = '/role';
            httpService.request("GET", path, null, function(result) {
                $scope.roleList = result.data;
            });
        }
        //获取用户单位
    $scope.getUnit = function() {
            var path = '/unit';
            httpService.request("GET", path, null, function(result) {
                $scope.unitList = result.data;
            });
        }
        //获取右侧model
    $scope.getRgtModel = function() {
            if (!$scope.activeId) {
                return
            }
            // $scope.getRecordList();
            $scope.getUserDetail($scope.activeId, true);
            $scope.getUserWorkCount();
        }
        //获取用户记录列表
    /*$scope.getRecordList = function() {
            if ($scope.recordBusy) return false;
            var path = '/record?userid=' + $scope.activeId + '&page=' + $scope.recordPage + '&limit=' + $scope.limit;
            $scope.recordBusy = true;
            httpService.request("GET", path, null, function(result) {
                angular.forEach(result.data, function(data, i) {
                    $scope.recordList.push(data);
                });
                if (result.data.length >= $scope.limit) {
                    $scope.recordBusy = false;
                    $scope.recordPage += 1;
                }
            });
        }*/
    $scope.groupList=function(){
        var path ='/group?page=1';
        httpService.request("GET", path, null, function(result){
            $scope.groupList=result.data;
        });
    }
    
    $scope.checkClick=function(Id,Name,isChecked){
        if(isChecked){
            $scope.userModel.Groups.push({
                "Id":Id,
                "Name":Name
            });
        }else{
            _.remove($scope.userModel.Groups, function(n) {
              return n.Id==Id&&n.Name==Name;
            });
        }
    }
    $scope.checked=function(Id,Groups){
        if(!Groups)
            return
        var newArr=_.filter(Groups, function(n) {
          return n.Id==Id;
        });
        if(newArr.length>0){
            return true
        }
    }
    $scope.initParam(); // 初始化查询列表变量
    $scope.getUserList();//获取用户列表
    $scope.getRole();//获取角色列表
    // $scope.getUnit();//用户单位
    $scope.groupList();//获取组别
});